package com.blue.code.ftl;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.blue.code.bean.EntityBean;
import com.blue.core.util.ReflectionUtil;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Component
public class ViewHandler implements Handler
{
private static Logger logger = LoggerFactory.getLogger(ViewHandler.class);
	
	@Value("${ftl.view_list}")
	private String list;
	@Value("${ftl.view_list_grid}")
	private String listGrid;
	@Value("${ftl.view_get}")
	private String get;
	@Value("${output.module}")
	private String module;
	
	private Template templateList;
	private Template templateListGrid;
	private Template templateGet;
	
	public ViewHandler()
	{
	}

	@Override
	public void handle(EntityBean bean, String output, String pkg) throws Exception
	{
		Map<String, Object> root = new HashMap<>();
		root.put("module", module);
		root.put("clazz", bean.getClazz());
		root.put("name", bean.getName());
		String field = ReflectionUtil.clazzToField(bean.getClazz());
		root.put("field", field);
		String view = ReflectionUtil.fieldToColumn(field);
		root.put("view", view);
		root.put("idList", bean.getIdList());
		root.put("columnList", bean.getColumnList());
		
		String fileNameList = String.format("%s/ftl/%s_list.ftl", output, view);
		File fileList = new File(fileNameList);
		File dir = fileList.getParentFile();
		if (!dir.exists())
			dir.mkdirs();
		String fileNameListGrid = String.format("%s/ftl/%s_list_grid.ftl", output, view);
		File fileListGrid = new File(fileNameListGrid);
		String fileNameGet = String.format("%s/ftl/%s_get.ftl", output, view);
		File fileGet = new File(fileNameGet);
		
		try (PrintWriter pwList = new PrintWriter(fileList, "UTF-8");
				PrintWriter pwListGrid = new PrintWriter(fileListGrid, "UTF-8");
				PrintWriter pwGet = new PrintWriter(fileGet, "UTF-8");)
		{
			templateList.process(root, pwList);
			logger.info("输出文件：{}", fileNameList);
			templateListGrid.process(root, pwListGrid);
			logger.info("输出文件：{}", fileNameListGrid);
			templateGet.process(root, pwGet);
			logger.info("输出文件：{}", fileNameGet);
		}
	}

	@Override
	public void initConfiguration(Configuration conf, String ext) throws Exception
	{
		String ftlList = list + ext;
		templateList = conf.getTemplate(ftlList);
		logger.info("初始化 View_List 模板：{}", ftlList);
		
		String ftlListGrid = listGrid + ext;
		templateListGrid = conf.getTemplate(ftlListGrid);
		logger.info("初始化 View_List_Grid 模板：{}", ftlListGrid);
		
		String ftlGet = get + ext;
		templateGet = conf.getTemplate(ftlGet);
		logger.info("初始化 View_Get 模板：{}", ftlGet);
	}
}
